<template>
	<div>
		<BreadCrumb pathOne="内容管理" pathTwo="心理知识管理"></BreadCrumb>
		<div>
			<el-form :inline="true">
				<el-form-item label="文章名" size="large">
					<el-input clearable size="large" v-model="searchName" style="width: 240px" placeholder="请输入文章名" />
				</el-form-item>

				<el-form-item label="选择作者" size="large">
					<el-select @clear="articleClassifyId = ''" clearable v-model="articleClassifyId" placeholder="无"
						size="large" style="width: 240px">
						<el-option v-for="(item, index) in AllClassify" :value="item.id" :label="item.consultName" />
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="query" size="large">搜索</el-button>
					<el-button type="primary" @click="createOrUpdate('')" size="large">新增</el-button>
					<el-button type="danger" size="large" @click="batchDelete">批量删除</el-button>
				</el-form-item>
			</el-form>

		</div>
		<div>
			<el-table :data="tableData" style="width: 100%;margin-top: 10px;"
				:header-cell-style="{ textAlign: 'center' }" :cell-style="{ textAlign: 'center' }"
				@selection-change="handleSelectionChange" border>
				<el-table-column type="selection" width="40" />
				<el-table-column fixed prop="id" label="id" width="50" />
				<el-table-column prop="title" label="文章名" width="200" show-overflow-tooltip />
				<el-table-column prop="introduction" label="文章简介" width="140" show-overflow-tooltip />
				<el-table-column prop="consultName" label="咨询师名" width="90" />
				<el-table-column label="缩略图" width="120">
					<template #default="scope">
						<el-avatar shape="square" size="large" :src="scope.row.url" />
					</template>
				</el-table-column>
				<el-table-column prop="psychologyTime" label="创建时间" width="180" />
				<el-table-column label="状态" width="70">
					<el-tag type="success">正常</el-tag>
				</el-table-column>
				<el-table-column fixed="right" label="操作" width="260">
					<template #default="scope">
						<el-button size="small" type="primary" @click="createOrUpdate(scope.row.id)">编辑</el-button>
						<el-button size="small" type="danger" @click="remove(scope.row.id)">删除</el-button>
						<el-button size="small" type="primary"
							@click="searchArticleDetails(scope.row.id)">查看详情内容</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
			:size="size" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
			@current-change="handleCurrentChange" />
		<el-dialog v-model="dialogFormVisible" :title="form.id == '' ? '新增' : '编辑'" width="700"
			style="margin-bottom: 60px;" @close="handleClose">
			<el-form>
				<el-form-item label="文章标题" label-width="auto" label-position='top'>
					<el-input size="large" v-model="form.title" autocomplete="off" placeholder="请输入文章标题" />
				</el-form-item>
				<el-form-item label="文章简介" label-width="auto" label-position='top'>
					<el-input size="large" v-model="form.introduction" autocomplete="off" placeholder="请输入文章简介" />
				</el-form-item>
				<el-form-item label="咨询师作者" size="large" label-position='top'>
					<el-select v-model="form.consultId" placeholder="无" size="large">
						<el-option v-for="(item, index) in AllClassify" :value="item.id" :label="item.consultName" />
					</el-select>
				</el-form-item>
				<el-form-item label="缩略图" label-position="top">
					<el-upload class="avatar-uploader" :action="baseURL+'upload'" :show-file-list="false"
						:on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" name="file">
						<img v-if="imageUrl" :src="imageUrl" class="avatar" />
						<el-icon v-else class="avatar-uploader-icon">
							<Plus />
						</el-icon>
					</el-upload>
				</el-form-item>
				<el-form-item label="文章内容详情" label-width="auto" label-position='top'>
					<QuillEditor v-model:content="form.content" contentType="html" :options="editorOptions" readonly
						:key="editorKey" style="min-height: 300px; border: 1px solid #ccc;width: 700px;" />
				</el-form-item>

			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="dialogFormVisible = false">取消</el-button>
					<el-button type="primary" @click="dialogFormVisible = false, add()">
						确定
					</el-button>
				</div>
			</template>
		</el-dialog>
		<el-dialog v-model="dialogArticleDetails" title="内容详情" width="700" style="margin-bottom: 60px;"
			@close="handleClose">
			<el-form-item label="" label-width="auto" label-position='top'>
				<QuillEditor v-model:content="form.content" contentType="html" :options="editorOptions" readonly
					:key="editorKey" style="min-height: 300px; border: 1px solid #ccc;width: 700px;" />
			</el-form-item>
		</el-dialog>
	</div>
</template>

<script setup>
	import {
		getCurrentInstance,
		onMounted,
		reactive,
		ref
	} from 'vue'
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'
	import {
		Plus
	} from '@element-plus/icons-vue'
	import BreadCrumb from "../../components/BreadCrumb.vue"
	import {
		QuillEditor
	} from '@vueup/vue-quill'
	import '@vueup/vue-quill/dist/vue-quill.snow.css'
	import http from '@/util/http';
	const baseURL = http.defaults.baseURL
	
	const content = ref('');
	const editorOptions = reactive({
		theme: 'snow', // 使用 snow 主题
		modules: {
			toolbar: [
				['bold', 'italic', 'underline', 'strike'], // 加粗、斜体、下划线、删
				['blockquote', 'code-block'], //引用，代码块
				[{
					'header': [1, 2, 3, 4, 5, 6, false]
				}], //几级标题
				[{
					'list': 'ordered'
				}, {
					'list': 'bullet'
				}], // 有序列表、无序列表
				[{
					'indent': '-1'
				}, {
					'indent': '+1'
				}], // 缩进
				[{
					'size': ['small', false, 'large', 'huge']
				}], // 字体大小
				[{
					'color': []
				}, {
					'background': []
				}], // 字体颜色，字体背景颜色
				[{
					'font': []
				}], //字体
				[{
					'align': []
				}], //对齐方式
				['link', 'image'] // 链接、图片
			]
		}
	})

	const editorKey = ref(0)
	const getMsg = (val) => {
		form.value.content = val
	}
	const AllClassify = ref([])
	const axios = getCurrentInstance().appContext.config.globalProperties.axios;

	const getAllClassify = () => {
		axios.get('/consult').then(resp => {
			AllClassify.value = resp.data
		})
	}
	const tableData = ref([])

	const articleClassifyId = ref('')
	const query = () => {
		axios.get(
			`psychologyKnowledge/findKnowledgePage?pageNum=${currentPage.value}&pageSize=${pageSize.value}&title=${searchName.value}&consultId=${articleClassifyId.value}`,
		).then(resp => {
			tableData.value = resp.data.list
			total.value = resp.data.total
			tableData.value.forEach(item => {
				item.url = item.url
			})
		})
	}
	const currentPage = ref(1) // 当前页
	const pageSize = ref(10) // 每页显示条目数
	const size = 'default' // 分页大小
	const total = ref(0)
	const handleSizeChange = (val) => {
		pageSize.value = val;
		query();
	}
	const handleCurrentChange = (val) => {
		currentPage.value = val
		query();
	}
	const searchName = ref('')
	const dialogFormVisible = ref(false)
	// const articleClassifyName = ref('')
	const handleClose = () => {
		form.value = {
			id: "",
			title: "",
			introduction: "",
			url: "",
			content: "",
			psychologyTime: "",
			consultId: "",
			del: 0
			//consultName: ""
		}
		imageUrl.value = ''
		editorKey.value++
	}
	const createOrUpdate = (id) => {
		dialogFormVisible.value = true
		if (id == '') {
			handleClose();
		} else {
			axios.get(
				`/psychologyKnowledge/findById/${id}`,
			).then(resp => {
				form.value = resp.data
				// resp.data.url为相对路径，展示时拼接完整路径
				imageUrl.value = resp.data.url
			})
		}
	}

	const form = ref({
		id: "",
		title: "",
		introduction: "",
		url: "",
		content: "",
		psychologyTime: "",
		consultId: "",
		del: 0
		//consultName: ""
	})
	const dialogArticleDetails = ref(false)
	const searchArticleDetails = (id) => {
		dialogArticleDetails.value = true
		if (id == '') {
			handleClose();
		} else {
			axios.get(
				`/psychologyKnowledge/findById/${id}`,
			).then(resp => {
				form.value = resp.data
			})
		}
	}
	const add = () => {
		if (form.value.id == '') {
			axios.post('psychologyKnowledge/add', form.value).then(resp => {
				if (resp.data.code == 200) {
					ElMessage({
						message: '新增成功',
						type: 'success',
					})
				} else {
					ElMessage.error('新增失败')
				}
			}).finally(() => {
				query();
			})
		} else {
			axios.put('psychologyKnowledge/edit', form.value).then(resp => {
				if (resp.code == 200) {
					ElMessage({
						message: '修改成功',
						type: 'success',
					})
				} else {
					ElMessage.error('修改失败')
				}
			}).finally(() => {
				query();
			})
		}
	}
	const remove = (id) => {
		ElMessageBox.confirm(
				'此操作将永久删除该文件, 是否继续?',
				'提示', {
					confirmButtonText: '确认',
					cancelButtonText: '取消',
					type: 'warning',
				}
			)
			.then(() => {
				axios.delete(`psychologyKnowledge/remove/${id}`).then((resp) => {
					if (resp.data.code == 200) {
						ElMessage({
							message: '删除成功',
							type: 'success',
						})
					} else {
						ElMessage.error('删除失败')
					}
				}).finally(() => {
					query();
				});
			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '取消删除',
				})
			})
	}
	const ids = ref('')
	const handleSelectionChange = (selection) => {
		ids.value = selection.map(item => item.id)
	}

	const batchDelete = () => {
		if (!ids.value.length) {
			ElMessage.info('请选择要删除的数据')
			return
		}
		ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		}).then(() => {
			axios.delete('psychologyKnowledge/removeBatch', {
				data: ids.value
			}).then(res => {
				ElMessage.success('删除成功')
				query();
			})
		}).catch(() => {
			ElMessage.info('已取消删除')
		}).finally(() => {
			query();
		});
	}
	const imageUrl = ref('')
	const handleAvatarSuccess = (response) => {
		// 后端返回的是相对路径，比如 "/upload/20250717/xxxx.jpg"
		form.value.url = response.data; // 只存储相对路径
		imageUrl.value = response.data; // 展示时拼接完整路径
	}
	const beforeAvatarUpload = (file) => {
		const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
		const isLt2M = file.size / 1024 / 1024 < 2;

		if (!isJPG) {
			this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
		}
		if (!isLt2M) {
			this.$message.error('上传头像图片大小不能超过 2MB!');
		}
		return isJPG && isLt2M;
	}

	onMounted(() => {
		query()
		getAllClassify()
	})
</script>

<style scoped>
	.avatar-uploader .avatar {
		width: 178px;
		height: 178px;
		display: block;
	}

	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}
</style>